package main

import (
	"Metro/config"
	"Metro/dal"
	"Metro/dal/query"
	"Metro/protocol/fas"
	"Metro/protocol/modbus"
	"context"
	"fmt"
	"github.com/panjf2000/gnet/v2"
	"jialiking.com/gaogang/common/utils"
	"os"
	"syscall"
	"time"
)

const ()

func main() {
	sigs := make(chan os.Signal)
	//signal.Notify(sigs)
	boot := make(chan string)
	go func() {
		utils.InfoLog("start fas server on port %d", config.FASPort)
		err := gnet.Run(&fas.Server, fmt.Sprintf("tcp://:%d", config.FASPort), gnet.WithMulticore(true), gnet.WithTicker(true), gnet.WithReuseAddr(true), gnet.WithReusePort(true), gnet.WithTCPKeepAlive(60*time.Second))
		if err != nil {
			boot <- "fail to run fas server"
			utils.ErrorLog("fail to start fas server: %v", err)
			return
		}
	}()
	go func() {
		utils.InfoLog("start modbus server on port %d", config.ModbusPort)
		err := gnet.Run(&modbus.Server, fmt.Sprintf("tcp://:%d", config.ModbusPort), gnet.WithMulticore(true), gnet.WithTicker(true), gnet.WithReuseAddr(true), gnet.WithReusePort(true), gnet.WithTCPKeepAlive(60*time.Second))
		if err != nil {
			boot <- "fail to run modbus server"
			utils.ErrorLog("fail to start fas server: %v", err)
			return
		}
	}()
	fas.Test()
	for {
		select {
		case msg := <-boot:
			utils.ErrorLog(msg)
			shutdownServers()
		case sig := <-sigs:
			utils.GlobalLog("receive signal: %v", sig)
			if sig == syscall.SIGTERM || sig == syscall.SIGINT {
				shutdownServers()
				return
			}
		}
	}
}

func shutdownServers() {
	err := fas.Server.Eng.Stop(context.Background())
	if err != nil {
		utils.ErrorLog("fail to stop fas server: %v", err)
	}
	err = modbus.Server.Eng.Stop(context.Background())
	if err != nil {
		utils.ErrorLog("fail to stop modbus server: %v", err)
	}
}

//var influxdbClient influxdb.Client

func init() {
	query.SetDefault(dal.DB)
	//var err error
	//influxdbClient, err = influxdb.NewHTTPClient(influxdb.HTTPConfig{
	//	Addr:    config.InfluxUrl,
	//	Timeout: (time.Duration(config.InfluxTimeout)) * time.Second,
	//})
	//if err != nil {
	//	panic("fail to init influx db")
	//}
	//
	//if _, _, err = influxdbClient.Ping(5 * time.Second); err != nil {
	//	panic("fail to init influx db")
	//}
}
